import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/common/langs/text_key.dart';
import 'package:oramemo/core/controllers/device_controller.dart';
import 'package:oramemo/generated/assets.dart';
import 'package:oramemo/pages/device/relation_select_page.dart';
import 'package:oramemo/pages/first/first_logic.dart';
import 'package:oramemo/pages/transcription/ai_transcription/ai_transcription_logic.dart';
import 'package:oramemo/widget/gradient_app_head.dart';
import 'package:oramemo/widget/gradient_background.dart';
import 'package:oramemo/widget/my_button.dart';

class DeviceInfoPage extends StatefulWidget {
  const DeviceInfoPage({Key? key}) : super(key: key);

  @override
  State<DeviceInfoPage> createState() => _DeviceInfoPageState();
}

class _DeviceInfoPageState extends State<DeviceInfoPage> {
  final DeviceController controller = Get.find();
  final TextEditingController _deviceNameController = TextEditingController();
  final RelationSelectController relationSelectController =
      Get.put(RelationSelectController());

  @override
  void dispose() {
    _deviceNameController.dispose();
    super.dispose();
  }

  void _goToNextStep() {
    // 处理下一步逻辑
    // Get.snackbar(
    //     '提示', '设备名称: ${_deviceNameController.text}, 关系: $_selectedRelation');
    // 可以在这里导航到下一个页面

    String deviceSn = Get.arguments;
    String? relationId =
        relationSelectController.selectedRelation?.id?.toString();
    _bindDevice(deviceSn, relationId);
  }

  Future<String> _getDeviceId() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    return androidInfo.device;
    // print('Android Device ID: ${androidInfo.androidId}'); // androidId 可能为空，在某些设备上可能返回null
    // print('Device ID: ${androidInfo.device}'); // 设备ID，通常是序列号，在某些设备上可能返回null或异常值
  }

  Future<void> _bindDevice(String deviceSn, String? relationId) async {
    try {
      final terminalId = await _getDeviceId();
      final Map<String, String> data = {
        "deviceSn": deviceSn,
        "terminalId": terminalId,
        "deviceName": _deviceNameController.text,
        "deviceRelationId": relationId ?? ''
      };
      Loading.show();
      await controller.bindDevice(data);
      final FirstLogic firstLogic = Get.find();
      firstLogic.loadData();
      Loading.dismiss();
    } catch (e) {
      Loading.dismiss();
      _showErrorDialog('${TextKey.deviceBindFailed.tr}$e');
    }
  }

  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(TextKey.error.tr),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(TextKey.confirm.tr),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        // 添加手势检测器，点击空白处收起键盘
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Column(
          children: [
            AppBar(title: const Text('时光机信息')),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      const SizedBox(height: 30),

                      // 头像
                      const Center(
                        child: IconX.image(
                          Assets.facilityHead2,
                          size: 80,
                          color: Color(0xFF888992),
                        ),
                      ),

                      const SizedBox(height: 14),

                      // 时光机名称输入框
                      Container(
                        decoration: BoxDecoration(
                          color: Color(0xFFF3F5F9),
                          borderRadius: BorderRadius.circular(32),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Align(
                              alignment: Alignment.centerLeft,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    left: 16.0, top: 16.0),
                                child: Text(
                                  '时光机名称',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                    color: Colors.black.withOpacity(0.8),
                                  ),
                                ),
                              ),
                            ),
                            TextField(
                              controller: _deviceNameController,
                              decoration: const InputDecoration(
                                hintText: '请输入时光机名称',
                                hintStyle: TextStyle(
                                  color: Color(0xFFAAAAAA),
                                  fontSize: 14,
                                ),
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.symmetric(
                                    horizontal: 16, vertical: 12),
                              ),
                            ),

                            const Divider(
                                height: 1,
                                thickness: 1,
                                color: Color(0xFFEEEEEF)),

                            // 用户关系选择
                            InkWell(
                              onTap: () async {
                                // _showRelationPicker();
                                // 打开关系选择页面
                                final result = await Get.to(() =>
                                    const RelationSelectPage(
                                        initialRelation: ''));

// 如果用户点击保存，result 将包含选择的关系
                                if (result != null) {
                                  // 处理选择的关系
                                  setState(() {

                                  });
                                }
                              },
                              child: Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 16.0, vertical: 16.0),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      '你是时光机使用者的',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w500,
                                        color: Colors.black.withOpacity(0.8),
                                      ),
                                    ),
                                    Row(
                                      children: [
                                        Text(
                                          relationSelectController
                                                  .selectedRelation
                                                  ?.relationName ??
                                              '',
                                          style: const TextStyle(
                                            fontSize: 16,
                                            color: Color(0xFF888992),
                                          ),
                                        ),
                                        const SizedBox(width: 8),
                                        const Icon(
                                          Icons.arrow_forward_ios,
                                          size: 16,
                                          color: Color(0xFF888992),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            const SizedBox(height: 120),

                            // 下一步按钮
                            MyButton(
                              minWidth: 185,
                              minHeight: 40,
                              radius: 12,
                              onPressed: _goToNextStep,
                              text: '确认',
                            ),

                            // 暂不填写
                            TextButton(
                              onPressed: _goToNextStep,
                              child: const Text(
                                '暂不填写',
                                style: TextStyle(
                                  color: Color(0xFF888992),
                                  fontSize: 14,
                                ),
                              ),
                            ),

                            const SizedBox(height: 20),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
